package g

import (
	"log"
	"time"

	"github.com/toolkits/pkg/net/httplib"
)

func N9ePush(items []*Sample) {
	debug := Config().Debug
	debugSample := Config().DebugSample

	if Config().SwitchHosts.Enabled {
		hosts := HostConfig().Hosts
		for i, sample := range items {
			ident, has := sample.Tags["ident"]
			if has {
				if hostname, ok := hosts[ident]; ok {
					items[i].Tags["ident"] = hostname
				}
			}
		}
	}

	if debug {
		for i := range items {
			if matchSample(items[i], debugSample) {
				log.Printf("-> %+v\n", items[i])
			}
		}
	}

	if Config().OpenTSDB.Enabled {
		opentsdbPush(items)
	}
}

func opentsdbPush(items []*Sample) {
	res, _, err := httplib.PostJSON(Config().OpenTSDB.Address, time.Duration(Config().OpenTSDB.Timeout)*time.Millisecond, items, nil)
	if err != nil {
		log.Println("push samples fail:", err)
	} else {
		log.Println("push samples succ:", string(res))
	}
}

func matchSample(sample *Sample, filter *DebugSampleConfig) bool {
	ident := sample.Tags["ident"]
	if len(filter.Idents) > 0 && !in_array(ident, filter.Idents) {
		return false
	}

	if len(filter.Metrics) > 0 && !in_array(sample.Metric, filter.Metrics) {
		return false
	}

	if len(filter.Tags) > 0 {
		for key := range filter.Tags {
			val, has := sample.Tags[key]
			if !has {
				return false
			}

			if val != filter.Tags[key] {
				return false
			}
		}
	}

	return true
}

func in_array(a string, array []string) bool {
	for _, v := range array {
		if a == v {
			return true
		}
	}
	return false
}
